#include "RequestManager.hpp"
#include "ClientManager.hpp"
#include "Message.hpp"
#include "DataProxy.h"
#include "Config.hpp"
#include <boost/thread/thread.hpp>


namespace netspy
{

	void RequestManager::generateRequests()
	{
		for(;;)
		{

			boost::this_thread::sleep(boost::posix_time::seconds(Config::getInstance().getCheckPeriod()));	
	

			if (ClientManager::getInstance().isClientUpdated())
			{
				clients = ClientManager::getInstance().getClients();
				serviceMap = ClientManager::getInstance().getClientServiceMap();
			}

			for(client_vec::const_iterator it=clients->begin(); it!=clients->end(); ++it)
			{
				Message *message = new Message();
				message->command=getCommandString(CHECK_STATUS);
				message->info=(*(*it));
				
				message_ptr mess(message);
				requests_.push(mess);
			}
		}

	}


	void RequestManager::saveResults()
	{
		for(;;)
                {
 		        boost::shared_ptr <DataProxy> db = DataProxy::getInstance();
			message_ptr mess;
                 	results_.waitAndPop(mess);
			
			if (ClientManager::getInstance().isServiceUpdated())
			{
				services = ClientManager::getInstance().getServices();
				serviceMap = ClientManager::getInstance().getClientServiceMap();
			}
			service_vec_ptr ss = (*serviceMap)[mess->info.hash];
			
			if(mess->service_list.empty())
			{
				for (service_vec::const_iterator it=ss->begin(); it!=ss->end(); ++it)
				{
					db->addRecord(mess->info.hash, (*it)->id, 2);
				}
			}             
			else
			{
				for (service_vec::const_iterator it=ss->begin(); it!=ss->end(); ++it)
                                {
                                        db->addRecord(mess->info.hash, (*it)->id, 1);
                                }
 	
			}          
                }

	}

        shared_msg RequestManager::getRequest()
	{
		shared_msg request;
		requests_.waitAndPop(request);
		return request;	
	}
        
	void RequestManager::storeResult(shared_msg result)
	{

		results_.push(result);		

	}
  	
	void RequestManager::run()
        {
		if(!isRunning_)
		{
                	clients = ClientManager::getInstance().getClients();
			services = ClientManager::getInstance().getServices();
			serviceMap = ClientManager::getInstance().getClientServiceMap();
                	requestHandler_ = boost::thread(boost::bind(&RequestManager::generateRequests,this));
			resultHandler_= boost::thread(boost::bind(&RequestManager::saveResults,this));
		}   
	
		isRunning_=true;     
	}


}




